package com.xx.chat_room.websocket;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author fanjj
 * @date 2017/11/1
 */

public class ChatRoomWebSocketHandler implements WebSocketHandler {
    private Logger logger = LoggerFactory.getLogger(ChatRoomWebSocketHandler.class);
    private static Map<WebSocketSession, String> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String roomId = session.getAttributes().get("roomId") + "";
        sessionMap.put(session, roomId);
        logger.info("afterConnectionEstablished:{},{}", roomId, session.getId());
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        logger.info("handleMessage:{},{}", message.toString(), session.getId());
        if (StringUtils.isBlank(message.getPayload().toString())) {
            return;
        }
        String roomId = session.getAttributes().get("roomId") + "";
        for (Map.Entry<WebSocketSession, String> entry : sessionMap.entrySet()) {
            if (roomId.equals(entry.getValue())) {
                WebSocketSession user = entry.getKey();
                if (user.isOpen()) {
                    InetAddress inetAddress = session.getRemoteAddress().getAddress();
                    TextMessage returnMessage = new TextMessage(message.getPayload() + "_" + inetAddress.getHostAddress());
                    user.sendMessage(returnMessage);
                }
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        sessionMap.remove(session);
        logger.info("handleTransportError:{},{}", exception.getMessage(), session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        sessionMap.remove(session);
        logger.info("afterConnectionClosed:{},{}", session.getId(), closeStatus.getReason());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
